<?php
class Application
{
	private $path;

	public $file;
	public $controller;
	public $action; 

	public function __construct()
	{
		$this->path = dirname($_SERVER['SCRIPT_FILENAME']) . '/controllers/';
	}

	public function run()
	{
		$this->getController();

		if (is_readable($this->file) == false)
		{
			// 404
			header("HTTP/1.1 404 Not Found");
			exit;
		}

		include $this->file;
		
		$class = $this->controller.'Controller';
		$controller = new $class();
		$controller->view = new View();

		if (is_callable(array($controller, $this->action)) == false)
		{
			$action = 'index';
		}
		else
		{
			$action = $this->action;
		}

		$controller->$action();
	}


	private function getController()
	{
		$route = (empty($_GET['rt'])) ? '' : $_GET['rt'];

		if (empty($route))
		{
			$route = 'index';
		}
		else
		{
			$parts = explode('/', $route);
			$this->controller = $parts[0];
			if(isset( $parts[1]))
			{
				$this->action = $parts[1];
			}
		}

		if (empty($this->controller))
		{
			$this->controller = 'Index';
		}

		if (empty($this->action))
		{
			$this->action = 'index';
		}

		$this->file = $this->path . $this->controller . 'Controller.php';
	}
}
?>